using BasicData.API.Application.Command;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 批量删除生产信息命令处理器
    /// </summary>
    public class BatchDeleteProductionInfoCommandHandler : IRequestHandler<BatchDeleteProductionInfoCommand, APIResult<bool>>
    {
        private readonly IBaseRepositroy<ProductionInfo> _productionInfoRepository;
        private readonly ILogger<BatchDeleteProductionInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productionInfoRepository">生产信息仓储</param>
        /// <param name="logger">日志</param>
        public BatchDeleteProductionInfoCommandHandler(
            IBaseRepositroy<ProductionInfo> productionInfoRepository,
            ILogger<BatchDeleteProductionInfoCommandHandler> logger)
        {
            _productionInfoRepository = productionInfoRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除生产信息命令
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>删除结果</returns>
        public async Task<APIResult<bool>> Handle(BatchDeleteProductionInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始批量删除生产信息，Id数量：{Count}", request.ProductionInfoIds.Count);

                // 查找要删除的生产信息
                var productionInfos = await _productionInfoRepository.GetAllAsync()
                    .Where(p => request.ProductionInfoIds.Contains(p.Id) && !p.IsDeleted)
                    .ToListAsync(cancellationToken);

                if (!productionInfos.Any())
                {
                    _logger.LogWarning("未找到要删除的生产信息记录");
                    return new APIResult<bool>
                    {
                        Code = ResultCode.删除失败,
                        Message = "未找到要删除的生产信息记录",
                        Data = false
                    };
                }

                // 执行批量软删除
                var now = DateTime.Now;
                foreach (var info in productionInfos)
                {
                    info.IsDeleted = true;
                    info.ModifiedBy = request.ModifiedBy ?? "system";
                    info.ModifiedTime = now;
                    _productionInfoRepository.Update(info);
                }

                // 保存更改
                await _productionInfoRepository.SaveAsync();

                _logger.LogInformation("成功批量软删除生产信息，实际删除数量：{Count}", productionInfos.Count);

                return new APIResult<bool>
                {
                    Code = ResultCode.删除成功,
                    Message = $"成功删除{productionInfos.Count}条生产信息",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除生产信息时发生错误");
                return new APIResult<bool>
                {
                    Code = ResultCode.删除失败,
                    Message = $"批量删除生产信息失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }
} 